package com.bigchun.seeland;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.Nullable;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
//import com.hyphenate.chat.ChatClient;
//import com.hyphenate.helpdesk.callback.Callback;
//import com.tencent.mm.opensdk.modelmsg.SendAuth;
//import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
//import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import bean.CodeBean;
import bean.ContentDataBean;
import myapp.MyApp;
import myview.CountDownButton;
import util.MyLog;
import util.PreferenceUtil;
import util.RequestManager;
import util.SystemStatusManager;
import android.app.AlertDialog.Builder;

public class LoginActivity extends BaseActivity implements View.OnClickListener {


    private LinearLayout ll_loginbycode;
    private EditText et_phone_bycode;
    private EditText et_code_bycode;
    private TextView tv_getcode;
    private CountDownButton tv_getcode2;
    private TextView tv_login_bypwd;
    private LinearLayout ll_loginbypwd;
    private EditText et_phone_bypwd;
    private EditText et_pwd_bypwd;
    private TextView tv_login_bycode;
    private TextView tv_login;
    private LinearLayout ll_register;
    private LinearLayout ll_third_login;
    private LinearLayout ll_login_byfacebook;
    private LinearLayout ll_login_bywx;
    private String logintype = "0";//0是快捷登陆（验证码登录），1是密码登陆
    private Context context;
    private LoginButton login_button;
    private TextView tv_login_forgetpwd;
    private MyApp myapp;
    private IWXAPI api;
    private CallbackManager callbackManager;
    private JSONObject dataFB;
    private String status;
    private String token;
    private String apptype;
    private TextView tv_welcome;
    private String textData;
    private ContentDataBean.DataBean textContent;
    private TextView tv_xieyi;
    private TextView tv_yinsi;
    private Dialog noticeDialog;
    private SharedPreferences sharedPreferences;
    private LinearLayout ll_bianma;
    private TextView tv_bianma;
    private List<CodeBean.DataBean> temcodesList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
        setTranslucentStatus();
        context = this;
        myapp = (MyApp) getApplicationContext();
        myapp.addDestoryActivity(LoginActivity.this, "登陆页面");
        callbackManager = CallbackManager.Factory.create();
        sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        textData = sharedPreferences.getString("textData", "");
        String isagree = sharedPreferences.getString("isagree", "");
        initView();
        initLin();
        if (!"1".equals(isagree)){
            showNoticeDialog();
        }
        if ("0".equals(apptype)){
        }else if ("1".equals(apptype)){
            getCodeData();
        }

    }

    private void initView() {
        ll_bianma = findViewById(R.id.ll_bianma);
        tv_bianma = findViewById(R.id.tv_bianma);
        tv_xieyi = findViewById(R.id.tv_xieyi);
        tv_yinsi = findViewById(R.id.tv_yinsi);
        ll_loginbycode = findViewById(R.id.ll_loginbycode);
        et_phone_bycode = findViewById(R.id.et_phone_bycode);
        et_code_bycode = findViewById(R.id.et_code_bycode);
        tv_getcode = findViewById(R.id.tv_getcode);
        tv_getcode2 = findViewById(R.id.tv_getcode2);
        tv_login_bypwd = findViewById(R.id.tv_login_bypwd);
        ll_loginbypwd = findViewById(R.id.ll_loginbypwd);
        et_phone_bypwd = findViewById(R.id.et_phone_bypwd);
        et_pwd_bypwd = findViewById(R.id.et_pwd_bypwd);
        tv_login_bycode = findViewById(R.id.tv_login_bycode);
        tv_login = findViewById(R.id.tv_login);
        ll_register = findViewById(R.id.ll_register);
        ll_third_login = findViewById(R.id.ll_third_login);
        ll_login_byfacebook = findViewById(R.id.ll_login_byfacebook);
        ll_login_bywx = findViewById(R.id.ll_login_bywx);
        login_button = findViewById(R.id.login_button);
        tv_login_forgetpwd = findViewById(R.id.tv_login_forgetpwd);
        tv_welcome = findViewById(R.id.tv_welcome);
        TextView tv_third_login = findViewById(R.id.tv_third_login);
        TextView tv_facebook = findViewById(R.id.tv_facebook);
        TextView tv_wx = findViewById(R.id.tv_wx);
        TextView tv_noaccount = findViewById(R.id.tv_noaccount);
        TextView tv_right_now_register = findViewById(R.id.tv_right_now_register);

        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            if ("0".equals(apptype)){
                tv_welcome.setText(textContent.getWelcome_into_wood());
                ll_bianma.setVisibility(View.GONE);
            }else if ("1".equals(apptype)){
                tv_welcome.setText(textContent.getWelcome_into_xiran());
                ll_bianma.setVisibility(View.VISIBLE);
            }
            et_phone_bycode.setHint(textContent.getInput_phone());
            et_code_bycode.setHint(textContent.getInput_code());
            tv_getcode.setText(textContent.getGet_code());
            tv_getcode2.setText(textContent.getGet_code());
            tv_login_bypwd.setText(textContent.getLogin_by_pwd());
            et_phone_bypwd.setHint(textContent.getInput_account());
            et_pwd_bypwd.setHint(textContent.getInput_pwd());
            tv_login_bycode.setText(textContent.getLogin_by_code());
            tv_login_forgetpwd.setText(textContent.getForget_pwd());
            tv_login.setText(textContent.getLogin());
            tv_noaccount.setText(textContent.getNo_account());
            tv_right_now_register.setText(textContent.getRegister_now());
            tv_third_login.setText(textContent.getLogin_by_third());
            tv_facebook.setText(textContent.getFacebook());
            tv_wx.setText(textContent.getWx());
        }



        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                AccessToken accessToken = loginResult.getAccessToken();
                String token = accessToken.getToken();
                String applicationId = accessToken.getApplicationId();
                String userId = accessToken.getUserId();
//                getLoginInfo(loginResult.getAccessToken());
                getfacebookData(userId);
                Log.e("FaceBook登录",token+"   "+applicationId+"    "+userId+"   登录token");
                Log.e("FaceBook登录",accessToken+"   登录token====");
                Toast.makeText(getApplicationContext(), getString(R.string.facebook_success), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(), getString(R.string.facebook_cancel), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException error) {
                String s = error.toString();
                Log.e("FaceBook登录", s);
                Toast.makeText(getApplicationContext(), getString(R.string.facebook_error), Toast.LENGTH_SHORT).show();
            }
        });
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {


                if (currentProfile != null) {
//                    Toast.makeText(getApplicationContext(), "个人信息 = " + currentProfile.getFirstName()+"   "+currentProfile.getName(), Toast.LENGTH_SHORT).show();
                    String name = currentProfile.getName();

                }
            }
        };


    }
    public void getLoginInfo( AccessToken accessToken ) {
        GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
                if (object != null) {
                    String id = object.optString("id");   //比如:1565455221565
                    String name = object.optString("name");  //比如：Zhang San
                    String gender = object.optString("gender");  //性别：比如 male （男）  female （女）
                    String emali = object.optString("email");  //邮箱：比如：56236545@qq.com

                    //获取用户头像
                    JSONObject object_pic = object.optJSONObject("picture");
                    JSONObject object_data = object_pic.optJSONObject("data");
                    String photo = object_data.optString("url");

                    //获取地域信息
                    String locale = object.optString("locale");   //zh_CN 代表中文简体

//                    Toast.makeText(LoginActivity.this, "" + object.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,link,gender,birthday,email,picture,locale,updated_time,timezone,age_range,first_name,last_name");
        request.setParameters(parameters);
        request.executeAsync() ;
    }

    private void initLin() {
        ll_bianma.setOnClickListener(this);
        tv_xieyi.setOnClickListener(this);
        tv_yinsi.setOnClickListener(this);
        tv_login_bypwd.setOnClickListener(this);
        tv_login_bycode.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        ll_register.setOnClickListener(this);
        ll_login_byfacebook.setOnClickListener(this);
        ll_login_bywx.setOnClickListener(this);
        tv_getcode.setOnClickListener(this);
        tv_getcode2.setOnClickListener(this);
        tv_login_forgetpwd.setOnClickListener(this);
        et_phone_bycode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                // 禁止EditText输入空格
                if (charSequence.toString().contains(" ")) {
                    String[] str = charSequence.toString().split(" ");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < str.length; i++) {
                        sb.append(str[i]);
                    }
                    et_phone_bycode.setText(sb.toString());
                    et_phone_bycode.setSelection(start);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        et_phone_bypwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                // 禁止EditText输入空格
                if (charSequence.toString().contains(" ")) {
                    String[] str = charSequence.toString().split(" ");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < str.length; i++) {
                        sb.append(str[i]);
                    }
                    et_phone_bypwd.setText(sb.toString());
                    et_phone_bypwd.setSelection(start);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        et_pwd_bypwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                // 禁止EditText输入空格
                if (charSequence.toString().contains(" ")) {
                    String[] str = charSequence.toString().split(" ");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < str.length; i++) {
                        sb.append(str[i]);
                    }
                    et_pwd_bypwd.setText(sb.toString());
                    et_pwd_bypwd.setSelection(start);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        /*login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Toast.makeText(getApplicationContext(), "facebook登录成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(), "facebook登录取消", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(getApplicationContext(), "facebook登录错误", Toast.LENGTH_SHORT).show();
            }
        });*/


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
        //此处可以根据两个Code进行判断，本页面和结果页面跳过来的值
        if (requestCode == 1 && resultCode == 3) {
            String result = data.getStringExtra("result");
            tv_bianma.setText("+"+result);
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.tv_login_bypwd:
                logintype = "1";
                ll_loginbypwd.setVisibility(View.VISIBLE);
                ll_loginbycode.setVisibility(View.GONE);
                break;
            case R.id.tv_login_bycode:
                logintype = "0";
                if ("0".equals(apptype)){
                    ll_loginbycode.setVisibility(View.GONE);
                }else if ("1".equals(apptype)){
                    ll_loginbycode.setVisibility(View.VISIBLE);
                }

                ll_loginbypwd.setVisibility(View.GONE);
                break;
            case R.id.tv_login:

                /*ChatClient.getInstance().login("hanbaby", "111111", new Callback() {
                    @Override
                    public void onSuccess() {
                        Log.e("环信客服云","登陆成功");
                        Intent intent = new Intent(context,LoginInputmsgActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onError(int code, String error) {
                        Log.e("环信客服云","登陆失败  "+code+"   error:"+error);
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }
                });*/
                if ("0".equals(logintype)) {
                    //快捷登陆
                    String phonebycode = et_phone_bycode.getText().toString().trim();
                    String code = et_code_bycode.getText().toString().trim();
                    loginbyCode(phonebycode, code);
                } else if ("1".equals(logintype)) {
                    //账号密码登录
                    String phone = et_phone_bypwd.getText().toString().trim();
                    String pwd = et_pwd_bypwd.getText().toString().trim();
                    loginbyPwd(phone, pwd);
                }


                break;
            case R.id.ll_register:
                intent = new Intent(context, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_login_byfacebook:
//                getfacebookData();
//                LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("user_friends", "public_profile"));
                LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile"));

                break;
            case R.id.ll_login_bywx:
                String appid = getString(R.string.weixin_appid);
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "none";
                api = WXAPIFactory.createWXAPI(LoginActivity.this, appid, true);
                api.registerApp(appid);
                api.sendReq(req);
                break;
            case R.id.tv_getcode2:
                String phone = et_phone_bycode.getText().toString().trim();
                Log.e("手机号", phone + "   手机号");
                getPhoneAuthCode(phone);
                break;
            case R.id.tv_login_forgetpwd:
                intent = new Intent(context, ForgetPwdActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_xieyi:
                intent = new Intent(context, WebviewForXieyiActivity.class);
                if ("0".equals(apptype)){
                    intent.putExtra("url", "https://seeland-wood.com/template/mood.html");
                }else if ("1".equals(apptype)){
                    intent.putExtra("url", "https://seeland-wood.com/template/seeland.html");
                }
                startActivity(intent);
                break;
            case R.id.tv_yinsi:
                intent = new Intent(context, WebviewForXieyiActivity.class);
                if ("0".equals(apptype)){
                    intent.putExtra("url", "https://seeland-wood.com/api/formula/privacy");
                }else if ("1".equals(apptype)){
                    intent.putExtra("url", "https://seeland-wood.com/api/formula/see_privacy");
                }

                startActivity(intent);
                break;
            case R.id.ll_bianma:
                //编码
                intent = new Intent(context,BianmaActivity.class);
                startActivityForResult(intent,1);
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void getfacebookData(String fid) {

        String url = myapp.getWebConfig()+"/api/user/fackbooklogin";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("fackbook_id", fid);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_GET, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    dataFB = jsonObject.getJSONObject("data");
                    status = dataFB.getString("status");
                    msg.arg1 = 5;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    /**
     * 发送验证码
     */
    private void getPhoneAuthCode(String phone) {
        String url = myapp.getWebConfig() + "/api/sms/send";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("mobile", phone);
        paramsMap.put("event", "mobilelogin");
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    /**
     * 验证码登陆
     */
    private void loginbyCode(String phone, String code) {
        String bianmacode = tv_bianma.getText().toString().trim();
        bianmacode = bianmacode.replace("+","");
        String url = myapp.getWebConfig() + "/api/user/mobilelogin";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("mobile", phone);
        paramsMap.put("captcha", code);
        paramsMap.put("is_material", apptype);
        paramsMap.put("country_code", bianmacode);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    JSONObject userinfo = data.getJSONObject("userinfo");

                    SharedPreferences spuserInfo = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
                    spuserInfo.edit().putString("username", userinfo.getString("username")).commit();
                    spuserInfo.edit().putString("nickname", userinfo.getString("nickname")).commit();
                    spuserInfo.edit().putString("mobile", userinfo.getString("mobile")).commit();
                    spuserInfo.edit().putString("score", userinfo.getString("score")).commit();
                    spuserInfo.edit().putString("token", userinfo.getString("token")).commit();
                    spuserInfo.edit().putString("user_id", userinfo.getString("user_id")).commit();
                    spuserInfo.edit().putString("level", userinfo.getString("level")).commit();
                    String language = PreferenceUtil.getString("language", "");
                    String templanuage = "";
                    if ("0".equals(userinfo.getString("language"))){
//                        spuserInfo.edit().putString("language", "zh").commit();
                        templanuage = "zh";
                    }else if ("1".equals(userinfo.getString("language"))){
                        templanuage = "en";
                    }else if ("2".equals(userinfo.getString("language"))){
                        templanuage = "ja";
                    }
                    if (!language.equals(templanuage)){
                        PreferenceUtil.commitString("language", language);
                    }

                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    /**
     * 账号密码登陆
     */
    private void loginbyPwd(String phone, String pwd) {
        String url = myapp.getWebConfig() + "/api/user/login";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("account", phone);
        paramsMap.put("password", pwd);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    JSONObject userinfo = data.getJSONObject("userinfo");

                    SharedPreferences spuserInfo = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
                    spuserInfo.edit().putString("username", userinfo.getString("username")).commit();
                    spuserInfo.edit().putString("nickname", userinfo.getString("nickname")).commit();
                    spuserInfo.edit().putString("mobile", userinfo.getString("mobile")).commit();
                    spuserInfo.edit().putString("score", userinfo.getString("score")).commit();
                    spuserInfo.edit().putString("token", userinfo.getString("token")).commit();
                    spuserInfo.edit().putString("user_id", userinfo.getString("user_id")).commit();
                    spuserInfo.edit().putString("level", userinfo.getString("level")).commit();
                    String language = PreferenceUtil.getString("language", "");
                    String templanuage = "";
                    if ("0".equals(userinfo.getString("language"))){
//                        spuserInfo.edit().putString("language", "zh").commit();
                        templanuage = "zh";
                    }else if ("1".equals(userinfo.getString("language"))){
                        templanuage = "en";
                    }else if ("2".equals(userinfo.getString("language"))){
                        templanuage = "ja";
                    }
                    if (!language.equals(templanuage)){
                        PreferenceUtil.commitString("language", language);
                    }
                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Intent intent = null;
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String str = (String) msg.obj;
                    Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    Toast.makeText(context, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    //这里判断是否倒计时结束，避免在倒计时时多次点击导致重复请求接口
                    tv_getcode2.settime(120000);
                    if (tv_getcode2.isFinish()) {
                        //发送验证码请求成功后调用
                        tv_getcode2.start();
                    }
                    break;
                case 3:
                    //验证码登录结果
                    sharedPreferences.edit().putString("isagree","1").commit();
                    intent = new Intent(context, MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 4:
                    //账号密码登录结果
                    sharedPreferences.edit().putString("isagree","1").commit();
                    intent = new Intent(context, MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 5:
                    try {
                        if ("0".equals(status)){
                                String fbId = dataFB.getString("facebook");
                            intent = new Intent(context, LoginInputmsgActivity.class);
                            intent.putExtra("fbid",fbId);
                            intent.putExtra("wxid","");
                            intent.putExtra("logintype","facebook");
                            startActivity(intent);
                        }else if ("1".equals(status)){
                            JSONObject useri = dataFB.getJSONObject("userinfo");
                            SharedPreferences spuserInfo = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
                            spuserInfo.edit().putString("username", useri.getString("username")).commit();
                            spuserInfo.edit().putString("nickname", useri.getString("nickname")).commit();
                            spuserInfo.edit().putString("mobile", useri.getString("mobile")).commit();
                            spuserInfo.edit().putString("score", useri.getString("score")).commit();
                            spuserInfo.edit().putString("token", useri.getString("token")).commit();
                            spuserInfo.edit().putString("user_id", useri.getString("user_id")).commit();
                            spuserInfo.edit().putString("level", useri.getString("level")).commit();
                            String language = PreferenceUtil.getString("language", "");
                            String templanuage = "";
                            if ("0".equals(useri.getString("language"))){
//                        spuserInfo.edit().putString("language", "zh").commit();
                                templanuage = "zh";
                            }else if ("1".equals(useri.getString("language"))){
                                templanuage = "en";
                            }else if ("2".equals(useri.getString("language"))){
                                templanuage = "ja";
                            }
                            if (!language.equals(templanuage)){
                                PreferenceUtil.commitString("language", language);
                            }
                            intent = new Intent(context, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }catch (Exception e){

                    }

                    break;
                case 6:
                    if (temcodesList.size() > 0){
                        tv_bianma.setText("+"+temcodesList.get(0).getCode());
                    }
                    break;
            }
        }
    };


    private ProfileTracker profileTracker;
    /**
     * 设置状态栏背景状态
     */
    public  void setTranslucentStatus()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window win =  getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }

    private void showNoticeDialog(){
        Builder builder = new Builder(context);
        builder.setTitle("服务协议和隐私政策");
        builder.setMessage("请你务必审慎阅读、充分理解\"服务协议”和“隐私政策”各条款，包括但不限于:为了向你提供内容展示，图片保存等服务，我们需要收集你的设备信息、操作日志等个人信息。你可以在“设置\"中查看、变更、删除个人信息并管理你的授权。\n" +
                "\n" +
                "你可阅读《服务协议》和《隐私政策》了解详细信息。如你同意，请点击“同意”开始接受我们的服务。");
        builder.setPositiveButton("同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                sharedPreferences.edit().putString("isagree","1").commit();
            }
        });
        builder.setNegativeButton("暂不使用", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                sharedPreferences.edit().putString("isagree","0").commit();
                finish();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.setCanceledOnTouchOutside(false);//可选，点击dialog其它地方dismiss无效


        noticeDialog.show();


    }
    /**
     * 编码
     */
    private void getCodeData() {
        temcodesList.clear();

        String url = myapp.getWebConfig() + "/api/index/code";
        HashMap<String, String> paramsMap = new HashMap<>();
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temcodesList = new Gson().fromJson(data.toString(), new TypeToken<List<CodeBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 6;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }else{
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

}
